package yunquan.wang.modules.base.service.impl;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

import javax.annotation.Resource;

import org.springframework.core.convert.ConversionService;
import org.springframework.data.jpa.domain.Specifications;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import yunquan.wang.base.constants.ClassType;
import yunquan.wang.base.dao.DaoUtils;
import yunquan.wang.core.service.ServiceException;
import yunquan.wang.modules.base.dao.CodeValueDao;
import yunquan.wang.modules.base.entity.CodeType;
import yunquan.wang.modules.base.entity.CodeValue;
import yunquan.wang.modules.base.service.AppCodeService;

@Service("appCodeService")
@Transactional(value = "jpaTransaction")
public class AppCodeServiceImpl extends CodeTypeServiceImpl implements
		AppCodeService {
	@Resource
	private CodeValueDao codeValueDao;
	@Resource
	ConversionService conversionService;

	@Override
	public CodeValue saveCodeValue(CodeValue entity) {
		CodeType type = codeTypeDao.findOne(entity.getCodeType().getId());
		entity.setCodeType(type);
		return codeValueDao.save(entity);
	}

	@Override
	public void deleteCodeValue(String id) {
		codeValueDao.delete(id);

	}

	@Override
	public CodeValue getCodeValue(String id) {
		return codeValueDao.findOne(id);
	}

	@Override
	public List<CodeValue> getCodeValues(String typeId) {
		return codeValueDao.findAll(Specifications.where(DaoUtils.eq(
				"codeType.id", typeId)));
	}

	@Override
	public String findNameByType(String name) {
		return codeTypeDao.findNameByType(name);
	}

	@Override
	public Set<CodeValue> getAllCodeValue(String type) {
		CodeType codeType = codeTypeDao.findOne(Specifications.where(DaoUtils
				.eq("type", type)));
		if (codeType == null)
			throw new ServiceException("此码表不存在，请检查码表类型是否有此值：" + type);
		String valueType = codeType.getValueType();
		Set<CodeValue> codeValues = codeType.getCodeValues();
		for (CodeValue value : codeValues) {
			String valueString = value.getStringValue();
			if (valueType.contains("string")) {
				value.setValue(valueString);
			} else {
				@SuppressWarnings("rawtypes")
				Class clazz = ClassType.valueOf(valueType).getValue();
				;
				value.setValue(conversionService.convert(valueString, clazz));
			}
		}
		return codeValues;
	}
}
